import axios from 'axios'
import { ElMessage } from 'element-plus'

const $http = axios.create({
  baseURL: import.meta.env.VITE_URL || '/api',
  timeout: 5000
})

// 请求拦截
$http.interceptors.request.use(function (config) {
  config.headers = config.headers || {}
  // 向请求头添加 token
  config.headers.token = sessionStorage.getItem('token') || ''
  return config
}, function (error) {
  return Promise.reject(error)
})

// 响应拦截
$http.interceptors.response.use(function (res) {
  const { data, meta } = res.data
  if(meta.status == 200 || meta.status == 201) {
    return data
  } else {
    ElMessage.error(meta.msg)
    return Promise.reject(new Error(meta.msg))
  }
}, function (error) {
  return Promise.reject(error)
})

export default $http
